package com.davioliveira.cantalk.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.davioliveira.cantalk.utils.Pessoa;
import com.davioliveira.cantalk.utils.Usuario;

public class UsuarioDAO {
	private SQLiteDatabase database;
	private OpenHelper dbHelper;

    public static final String TABLE_NAME = "usuario";
    public static final String NOME = "nome";
    public static final String FOTO = "foto";
    public static final String ID = "id";
    
	private String[] allColumns = { NOME, FOTO,ID };

	public UsuarioDAO(Context context) {
		dbHelper = new OpenHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
		database.close();
		database = null;
	}

	public long insert(Usuario user) {
		ContentValues values = new ContentValues();
		values.put(NOME, user.getNome());
		values.put(FOTO, user.getFoto());
		values.put(ID, user.getID());

		return database.insert(TABLE_NAME, null, values);
	}
	
	public long update(Usuario user) {
		ContentValues values = new ContentValues();
		values.put(NOME, user.getNome());
		values.put(FOTO, user.getFoto());
		//values.put(ID, user.getID());

		return database.update(TABLE_NAME, values, ID + " = '" + user.getID() + "'", null);
	}

//	public boolean delete(Usuario user) {
//		long wReturn = database.delete(TABLE_NAME, ID + " = '" + user.getID() + "'", null);
//		if(wReturn == 0) {
//			return false;
//		} else {
//			return true;
//		}
//	}

	public Usuario read(String id) {
		Usuario user;
		
		Cursor c = database.query(TABLE_NAME, allColumns, ID + " = '" + id + "'", null,null, null, null); 
		if(c.moveToFirst()) {
			
			int indexNome = c.getColumnIndex(NOME);
			int indexFoto = c.getColumnIndex(FOTO);
			int indexID = c.getColumnIndex(ID);
			
			user = new Usuario();
			user.setNome(c.getString(indexNome));
			user.setFoto(c.getString(indexFoto));
			user.setID(c.getString(indexID));
			
			return user;
		} else {
			return null;
		}
	}
	
	public Usuario readAll() {
		Usuario user = new Usuario();
		
		Cursor c = database.query(TABLE_NAME, allColumns, null, null, null, null, null);
		if(c.moveToFirst()) {
			
			int indexNome = c.getColumnIndex(NOME);
			int indexFoto = c.getColumnIndex(FOTO);
			int indexID = c.getColumnIndex(ID);
			
			do {
				
				user.setNome(c.getString(indexNome));
				user.setFoto(c.getString(indexFoto));
				
			} while(c.moveToNext());
		}
		
		c.close();
		
		return user;
	}
}
